
package com.seekting.study;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

public class TestSocketClient {

    public static void main(String args[]) throws Exception {
        String ip = getAddress();

        open(ip);

    }

    private static String getAddress() {
        String ip = null;
        try {
            // 拿到所有ip地址
            Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
            while (enumeration.hasMoreElements()) {
                NetworkInterface elem = enumeration.nextElement();
                Enumeration<InetAddress> addresses = elem.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress inetAddress = (InetAddress) addresses.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        if (inetAddress.isSiteLocalAddress()) {
                            ip = inetAddress.getHostAddress();
                            // System.out.println(ip);
                        }
                    }

                }

            }
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return ip;
        // NetworkInterface networkInterface=
    }

    private static void open(String ip) throws UnknownHostException, IOException {
        // 为了简单起见，所有的异常都直接往外抛
        String host = "127.0.0.1"; // 要连接的服务端IP地址
        int port = 8899; // 要连接的服务端对应的监听端口
        // 与服务端建立连接
        Socket client = new Socket(host, port);
        // 建立连接后就可以往服务端写数据了
        Writer writer = new OutputStreamWriter(client.getOutputStream());
        writer.write("Hello Server.");
        writer.write("Hello Server1");
        writer.write("Hello Server2");
        writer.flush();// 写完后要记得flush
        writer.close();
        client.close();
    }
}
